package com.acmen.easyapi.repository;

import com.acmen.easyapi.dbcp.JdbcService;
import com.acmen.easyapi.model.PressureTest;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author acmen
 */
@Component
public class PressureTestRepository {

    private final static String QUERY_SQL = "select * from t_pressure_test where app_name=? order by create_dt desc limit 30";
    private final static String QUERY_SINGLE_ROW_SQL = "select * from t_pressure_test where id=? ";
    private final static String INSERT_SQL = "insert into t_pressure_test(id,app_name,name,base_path,create_dt,concurrency,headers) values(?,?,?,?,?,?,?)";
    private final static String DELETE_SQL = "delete from t_pressure_test where id=?";
    @Resource
    private JdbcService jdbcService;

    /**
     * 根据应用ID查询出测试记录
     *
     * @param appName
     * @return
     */
    public List<PressureTest> selectListByAppName(String appName) {
        List<PressureTest> pressureTests = jdbcService.selectList(QUERY_SQL, new Object[]{appName}, PressureTest.class);
        return pressureTests;
    }

    public PressureTest selectOne(String id){
        PressureTest pressureTest =  jdbcService.selectOne(QUERY_SINGLE_ROW_SQL, new Object[]{id}, PressureTest.class);
        return pressureTest;
    }

    /**
     * 保存压测结果
     * id,app_id,name,base_path,create_dt,concurrency,headers,aggregate_reports
     *
     * @param test
     * @return
     */
    public boolean save(PressureTest test) {
        Object[] args = {test.getId(), test.getAppName(), test.getName(), test.getBasePath(), test.getCreateDt(), test.getConcurrency(), JSON.toJSONString(test.getHeaders())};
        return jdbcService.update(INSERT_SQL, args) > 0;
    }

    /**
     * 删除组合测试
     *
     * @param id
     * @return
     */
    public boolean delete(String id) {
        return jdbcService.update(DELETE_SQL, new Object[]{id}) > 0;
    }

}
